package com.qo.qsdk.ui.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.webkit.WebView;

import com.qo.qsdk.utils.QSDKHelper;

public class CornersWebView extends WebView {

    private int mViewWidth;
    private int mViewHeight;
    private float[] mRadiusArray = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f};

    public CornersWebView(Context context) {
        super(context);
        init(context, null);
    }

    public CornersWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CornersWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {

        float mTopLeft = QSDKHelper.dip2px(context, 0);
        float mTopRight = QSDKHelper.dip2px(context, 0);
        float mBottomLeft = QSDKHelper.dip2px(context, 0);
        float mBottomRight = QSDKHelper.dip2px(context, 0);
        setRadius(mTopLeft, mTopRight, mBottomRight, mBottomLeft);
    }

    public void setRadius(float leftTop, float rightTop, float rightBottom, float leftBottom) {
        mRadiusArray[0] = leftTop;
        mRadiusArray[1] = leftTop;
        mRadiusArray[2] = rightTop;
        mRadiusArray[3] = rightTop;
        mRadiusArray[4] = rightBottom;
        mRadiusArray[5] = rightBottom;
        mRadiusArray[6] = leftBottom;
        mRadiusArray[7] = leftBottom;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mViewWidth = getMeasuredWidth();
        mViewHeight = getMeasuredHeight();
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        int mX = this.getScrollX();
        int mY = this.getScrollY();
        Path path = new Path();
        path.addRoundRect(new RectF(0, mY, mX + mViewWidth, mY + mViewHeight), mRadiusArray, Path.Direction.CW);
        canvas.clipPath(path);
        super.onDraw(canvas);
    }
}
